﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;

namespace VideoPlayer
{
    public partial class VideoFrameControl : UserControl
    {
        public VideoFrameControl()
        {
            InitializeComponent();
        }
        object sync = new object();

        public long indexTime { get; set; }

        private long indexFrame { get; set; } = 0;
        protected override void OnPaint(PaintEventArgs e)
        {
            //base.OnPaint(e);
            lock (sync)
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                if (Data.bitmaps.Count() == 0)
                    return;
                Graphics g = e.Graphics;
                g.Clear(Color.Black);
                Bitmap bitmap = null;
                var dic = Data.bitmaps.Dequeue();
                indexTime = dic.Key;
                bitmap = dic.Value;
                indexFrame++;
                Size imageSize = bitmap.Size;
                Point p = CalculationPoint(ref imageSize);
                g.DrawString("indexFrame:" + indexFrame, new Font("宋体", 9f), Brushes.Red, new PointF(10, 10));
                g.DrawImage(bitmap, new Rectangle(p, imageSize));
                stopwatch.Stop();
                Console.WriteLine(stopwatch.ElapsedMilliseconds);
            }
        }

        /// <summary>
        /// 计算坐标位置
        /// </summary>
        /// <returns></returns>
        private Point CalculationPoint(ref Size imageSize)
        {
            //图片 长宽比 比 容器长宽比 大 则图片宽度等于容器宽度，反之图片高度等于容器高度
            double imgB = (double)imageSize.Width / (double)imageSize.Height;
            double picB = (double)this.Size.Width / (double)this.Size.Height;
            if (imgB > picB)
            {
                imageSize.Width = this.Size.Width;
                imageSize.Height = (int)(imageSize.Width / imgB);
                return new Point(0, (this.Size.Height - imageSize.Height) / 2);
            }
            else
            {
                imageSize.Height = this.Size.Height;
                imageSize.Width = (int)(imageSize.Height * imgB);
                return new Point((this.Size.Width - imageSize.Width) / 2, 0);
            }
        }
    }
}
